<template>
  <div class="purchase-statistics">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800">采购统计分析</h1>
      <div class="flex items-center space-x-4">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="refreshData" :icon="Refresh">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-blue-100 text-blue-600">
            <el-icon size="24"><Money /></el-icon>
          </div>
          <div class="ml-4">
            <p class="text-sm text-gray-600">总采购金额</p>
            <p class="text-2xl font-bold text-blue-600">¥{{ totalAmount.toLocaleString() }}</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-green-100 text-green-600">
            <el-icon size="24"><Document /></el-icon>
          </div>
          <div class="ml-4">
            <p class="text-sm text-gray-600">采购订单数</p>
            <p class="text-2xl font-bold text-green-600">{{ totalOrders }}</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-orange-100 text-orange-600">
            <el-icon size="24"><OfficeBuilding /></el-icon>
          </div>
          <div class="ml-4">
            <p class="text-sm text-gray-600">合作供应商</p>
            <p class="text-2xl font-bold text-orange-600">{{ totalSuppliers }}</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-purple-100 text-purple-600">
            <el-icon size="24"><Box /></el-icon>
          </div>
          <div class="ml-4">
            <p class="text-sm text-gray-600">采购商品种类</p>
            <p class="text-2xl font-bold text-purple-600">{{ totalProducts }}</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- 采购金额趋势图 -->
      <el-card>
        <template #header>
          <div class="flex justify-between items-center">
            <span class="text-lg font-semibold">采购金额趋势</span>
            <el-radio-group v-model="trendPeriod" size="small" @change="updateTrendChart">
              <el-radio-button label="week">周</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
              <el-radio-button label="quarter">季度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="trendChartRef" class="chart-container"></div>
      </el-card>

      <!-- 采购分类占比 -->
      <el-card>
        <template #header>
          <span class="text-lg font-semibold">采购分类占比</span>
        </template>
        <div ref="categoryChartRef" class="chart-container"></div>
      </el-card>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- 供应商采购排行 -->
      <el-card>
        <template #header>
          <span class="text-lg font-semibold">供应商采购排行</span>
        </template>
        <div ref="supplierChartRef" class="chart-container"></div>
      </el-card>

      <!-- 月度采购对比 -->
      <el-card>
        <template #header>
          <span class="text-lg font-semibold">月度采购对比</span>
        </template>
        <div ref="monthlyChartRef" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 详细数据表格 -->
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-semibold">采购明细统计</span>
          <el-button type="primary" size="small" @click="exportData" :icon="Download">
            导出数据
          </el-button>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="供应商统计" name="supplier">
          <el-table :data="supplierStats" stripe>
            <el-table-column prop="rank" label="排名" width="80" />
            <el-table-column prop="supplierName" label="供应商名称" min-width="150" />
            <el-table-column prop="orderCount" label="订单数量" width="100" />
            <el-table-column prop="totalAmount" label="采购金额" width="120">
              <template #default="{ row }">
                <span class="text-green-600 font-semibold">¥{{ row.totalAmount.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="avgAmount" label="平均订单金额" width="140">
              <template #default="{ row }">
                ¥{{ row.avgAmount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="percentage" label="占比" width="100">
              <template #default="{ row }">
                <span class="text-blue-600">{{ row.percentage }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="lastOrderDate" label="最近采购" width="120" />
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="商品统计" name="product">
          <el-table :data="productStats" stripe>
            <el-table-column prop="rank" label="排名" width="80" />
            <el-table-column prop="productName" label="商品名称" min-width="150" />
            <el-table-column prop="category" label="分类" width="100" />
            <el-table-column prop="quantity" label="采购数量" width="100" />
            <el-table-column prop="totalAmount" label="采购金额" width="120">
              <template #default="{ row }">
                <span class="text-green-600 font-semibold">¥{{ row.totalAmount.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="avgPrice" label="平均单价" width="120">
              <template #default="{ row }">
                ¥{{ row.avgPrice.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="percentage" label="占比" width="100">
              <template #default="{ row }">
                <span class="text-blue-600">{{ row.percentage }}%</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="月度统计" name="monthly">
          <el-table :data="monthlyStats" stripe>
            <el-table-column prop="month" label="月份" width="100" />
            <el-table-column prop="orderCount" label="订单数量" width="100" />
            <el-table-column prop="totalAmount" label="采购金额" width="120">
              <template #default="{ row }">
                <span class="text-green-600 font-semibold">¥{{ row.totalAmount.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="avgAmount" label="平均订单金额" width="140">
              <template #default="{ row }">
                ¥{{ row.avgAmount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="growth" label="环比增长" width="120">
              <template #default="{ row }">
                <span :class="row.growth >= 0 ? 'text-green-600' : 'text-red-600'">
                  {{ row.growth >= 0 ? '+' : '' }}{{ row.growth }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="supplierCount" label="合作供应商" width="120" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  Money,
  Document,
  OfficeBuilding,
  Box,
  Download
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const dateRange = ref([])
const trendPeriod = ref('month')
const activeTab = ref('supplier')

// 图表引用
const trendChartRef = ref()
const categoryChartRef = ref()
const supplierChartRef = ref()
const monthlyChartRef = ref()

// 图表实例
let trendChart: echarts.ECharts | null = null
let categoryChart: echarts.ECharts | null = null
let supplierChart: echarts.ECharts | null = null
let monthlyChart: echarts.ECharts | null = null

// 统计数据
const totalAmount = ref(0)
const totalOrders = ref(0)
const totalSuppliers = ref(0)
const totalProducts = ref(0)

// 表格数据
const supplierStats = ref([])
const productStats = ref([])
const monthlyStats = ref([])

// 初始化统计数据
const initStatsData = () => {
  totalAmount.value = 1250000
  totalOrders.value = 156
  totalSuppliers.value = 28
  totalProducts.value = 89
  
  // 供应商统计数据
  supplierStats.value = [
    {
      rank: 1,
      supplierName: '北京科技有限公司',
      orderCount: 45,
      totalAmount: 450000,
      avgAmount: 10000,
      percentage: 36.0,
      lastOrderDate: '2024-02-15'
    },
    {
      rank: 2,
      supplierName: '上海制造集团',
      orderCount: 38,
      totalAmount: 380000,
      avgAmount: 10000,
      percentage: 30.4,
      lastOrderDate: '2024-02-14'
    },
    {
      rank: 3,
      supplierName: '广州贸易公司',
      orderCount: 32,
      totalAmount: 280000,
      avgAmount: 8750,
      percentage: 22.4,
      lastOrderDate: '2024-02-13'
    },
    {
      rank: 4,
      supplierName: '深圳电子科技',
      orderCount: 25,
      totalAmount: 140000,
      avgAmount: 5600,
      percentage: 11.2,
      lastOrderDate: '2024-02-12'
    }
  ]
  
  // 商品统计数据
  productStats.value = [
    {
      rank: 1,
      productName: '笔记本电脑',
      category: '电子设备',
      quantity: 85,
      totalAmount: 425000,
      avgPrice: 5000,
      percentage: 34.0
    },
    {
      rank: 2,
      productName: '办公桌',
      category: '办公家具',
      quantity: 120,
      totalAmount: 240000,
      avgPrice: 2000,
      percentage: 19.2
    },
    {
      rank: 3,
      productName: '打印机',
      category: '办公设备',
      quantity: 45,
      totalAmount: 180000,
      avgPrice: 4000,
      percentage: 14.4
    },
    {
      rank: 4,
      productName: '办公椅',
      category: '办公家具',
      quantity: 200,
      totalAmount: 160000,
      avgPrice: 800,
      percentage: 12.8
    }
  ]
  
  // 月度统计数据
  monthlyStats.value = [
    {
      month: '2024-02',
      orderCount: 45,
      totalAmount: 450000,
      avgAmount: 10000,
      growth: 15.2,
      supplierCount: 12
    },
    {
      month: '2024-01',
      orderCount: 38,
      totalAmount: 380000,
      avgAmount: 10000,
      growth: -5.8,
      supplierCount: 10
    },
    {
      month: '2023-12',
      orderCount: 42,
      totalAmount: 420000,
      avgAmount: 10000,
      growth: 8.5,
      supplierCount: 11
    },
    {
      month: '2023-11',
      orderCount: 35,
      totalAmount: 350000,
      avgAmount: 10000,
      growth: -12.5,
      supplierCount: 9
    }
  ]
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const data = params[0]
        return `${data.name}<br/>采购金额: ¥${data.value.toLocaleString()}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => `¥${(value / 10000).toFixed(0)}万`
      }
    },
    series: [
      {
        name: '采购金额',
        type: 'line',
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(59, 130, 246, 0.3)' },
            { offset: 1, color: 'rgba(59, 130, 246, 0.05)' }
          ])
        },
        lineStyle: {
          color: '#3b82f6'
        },
        itemStyle: {
          color: '#3b82f6'
        },
        data: [320000, 380000, 420000, 350000, 450000, 480000, 520000, 490000, 460000, 510000, 480000, 450000]
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化分类图表
const initCategoryChart = () => {
  if (!categoryChartRef.value) return
  
  categoryChart = echarts.init(categoryChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '采购分类',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 425000, name: '电子设备', itemStyle: { color: '#3b82f6' } },
          { value: 400000, name: '办公家具', itemStyle: { color: '#10b981' } },
          { value: 180000, name: '办公设备', itemStyle: { color: '#f59e0b' } },
          { value: 120000, name: '办公用品', itemStyle: { color: '#ef4444' } },
          { value: 125000, name: '其他', itemStyle: { color: '#8b5cf6' } }
        ]
      }
    ]
  }
  
  categoryChart.setOption(option)
}

// 初始化供应商图表
const initSupplierChart = () => {
  if (!supplierChartRef.value) return
  
  supplierChart = echarts.init(supplierChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params: any) => {
        const data = params[0]
        return `${data.name}<br/>采购金额: ¥${data.value.toLocaleString()}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => `¥${(value / 10000).toFixed(0)}万`
      }
    },
    yAxis: {
      type: 'category',
      data: ['深圳电子科技', '广州贸易公司', '上海制造集团', '北京科技有限公司']
    },
    series: [
      {
        name: '采购金额',
        type: 'bar',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#3b82f6' },
            { offset: 1, color: '#1d4ed8' }
          ])
        },
        data: [140000, 280000, 380000, 450000]
      }
    ]
  }
  
  supplierChart.setOption(option)
}

// 初始化月度对比图表
const initMonthlyChart = () => {
  if (!monthlyChartRef.value) return
  
  monthlyChart = echarts.init(monthlyChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        let result = `${params[0].name}<br/>`
        params.forEach((item: any) => {
          result += `${item.seriesName}: ${item.seriesName === '采购金额' ? '¥' + item.value.toLocaleString() : item.value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['采购金额', '订单数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['11月', '12月', '1月', '2月']
    },
    yAxis: [
      {
        type: 'value',
        name: '采购金额',
        position: 'left',
        axisLabel: {
          formatter: (value: number) => `¥${(value / 10000).toFixed(0)}万`
        }
      },
      {
        type: 'value',
        name: '订单数量',
        position: 'right'
      }
    ],
    series: [
      {
        name: '采购金额',
        type: 'bar',
        yAxisIndex: 0,
        itemStyle: {
          color: '#3b82f6'
        },
        data: [350000, 420000, 380000, 450000]
      },
      {
        name: '订单数量',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        itemStyle: {
          color: '#10b981'
        },
        lineStyle: {
          color: '#10b981'
        },
        data: [35, 42, 38, 45]
      }
    ]
  }
  
  monthlyChart.setOption(option)
}

// 更新趋势图表
const updateTrendChart = () => {
  if (!trendChart) return
  
  let data: number[]
  let xAxisData: string[]
  
  switch (trendPeriod.value) {
    case 'week':
      xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      data = [45000, 52000, 48000, 61000, 55000, 40000, 35000]
      break
    case 'quarter':
      xAxisData = ['Q1', 'Q2', 'Q3', 'Q4']
      data = [1120000, 1350000, 1480000, 1250000]
      break
    default: // month
      xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      data = [320000, 380000, 420000, 350000, 450000, 480000, 520000, 490000, 460000, 510000, 480000, 450000]
  }
  
  trendChart.setOption({
    xAxis: {
      data: xAxisData
    },
    series: [{
      data: data
    }]
  })
}

// 处理日期范围变化
const handleDateChange = (dates: any) => {
  if (dates && dates.length === 2) {
    ElMessage.success('日期范围已更新，正在刷新数据...')
    refreshData()
  }
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已刷新')
  // 这里可以重新获取数据并更新图表
}

// 处理标签页切换
const handleTabChange = (tabName: string) => {
  console.log('切换到标签页:', tabName)
}

// 导出数据
const exportData = () => {
  ElMessage.success('数据导出功能开发中...')
}

// 窗口大小变化时重新调整图表
const handleResize = () => {
  trendChart?.resize()
  categoryChart?.resize()
  supplierChart?.resize()
  monthlyChart?.resize()
}

// 组件挂载时初始化
onMounted(async () => {
  initStatsData()
  
  await nextTick()
  
  initTrendChart()
  initCategoryChart()
  initSupplierChart()
  initMonthlyChart()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
const cleanup = () => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  categoryChart?.dispose()
  supplierChart?.dispose()
  monthlyChart?.dispose()
}

// 在组件卸载时清理资源
if (typeof window !== 'undefined') {
  window.addEventListener('beforeunload', cleanup)
}
</script>

<style scoped>
.purchase-statistics {
  padding: 20px;
}

.stat-card {
  transition: transform 0.2s ease-in-out;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.grid {
  display: grid;
}

.grid-cols-1 {
  grid-template-columns: repeat(1, minmax(0, 1fr));
}

.grid-cols-2 {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

.grid-cols-4 {
  grid-template-columns: repeat(4, minmax(0, 1fr));
}

.gap-6 {
  gap: 1.5rem;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

.text-2xl {
  font-size: 1.5rem;
  line-height: 2rem;
}

.text-lg {
  font-size: 1.125rem;
  line-height: 1.75rem;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.font-bold {
  font-weight: 700;
}

.font-semibold {
  font-weight: 600;
}

.text-gray-800 {
  color: #1f2937;
}

.text-gray-600 {
  color: #4b5563;
}

.text-blue-600 {
  color: #2563eb;
}

.text-green-600 {
  color: #059669;
}

.text-orange-600 {
  color: #ea580c;
}

.text-purple-600 {
  color: #9333ea;
}

.text-red-600 {
  color: #dc2626;
}

.bg-blue-100 {
  background-color: #dbeafe;
}

.bg-green-100 {
  background-color: #dcfce7;
}

.bg-orange-100 {
  background-color: #fed7aa;
}

.bg-purple-100 {
  background-color: #e9d5ff;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.space-x-4 > * + * {
  margin-left: 1rem;
}

.ml-4 {
  margin-left: 1rem;
}

@media (min-width: 768px) {
  .md\:grid-cols-2 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (min-width: 1024px) {
  .lg\:grid-cols-2 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
  
  .lg\:grid-cols-4 {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}
</style>